#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
'''
@File    :   auth.py
@Time    :   2023/11/15 16:58:29
@Author  :   windstarry 
@Version :   1.0
'''
# here put the import lib
import re
from utils.jwt import Jwt
from backend.settings import SECRET_KEY
from ninja.security import HttpBearer
from ninja.errors import HttpError
from system.models import Role
from casbin_adapter.enforcer import enforcer


def get_user_info_from_token(request):
    # 从请求中获取token
    token = request.META.get("HTTP_AUTHORIZATION")
    # 将token按空格分割并取第二个元素
    token = token.split(" ")[1]
    # 创建Jwt对象
    jwt = Jwt(SECRET_KEY)
    # 使用SECRET_KEY和token解码获取值
    value = jwt.decode(SECRET_KEY, token)
    # 获取解码后的payload作为用户信息
    user_info = value.payload
    # 返回用户信息
    return user_info


class GlobalAuth(HttpBearer):
    def authenticate(self, request, token):
        method = request.META.get("REQUEST_METHOD")
        path = request.META.get("PATH_INFO")
        jwt = Jwt(SECRET_KEY)
        value = jwt.decode(SECRET_KEY, token)
        user_info = value.payload
        # 如果是超级管理员
        if user_info["is_superuser"]:
            return True
        else:
            # 判断是path是否是/数字结尾
            result = re.search(r'/\d+$', path)
            if result:
                match_value = result.group()
                # 将数字结尾的接口替换成.*? 因为接口中是/{id}
                path = path.replace(match_value, '/*')
            for role in user_info["role"]:
                role_info = Role.objects.get(id=role)
                if enforcer.enforce(role_info.code, path, method):
                    return True
        raise HttpError(502, "没有权限")